import { Component } from '@angular/core';
import {IonicPage, NavController, NavParams} from 'ionic-angular';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {UserInfoService} from "../../../services/userInfo.service";
import {CustomValidators} from "ng2-validation";
import {AppService} from "../../../services/app.service";
import {CityDataProvider} from "../../../providers/city-data/city-data";

/**
 * Generated class for the UserInfoEditPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-user-info-edit',
  templateUrl: 'user-info-edit.html',
})
export class UserInfoEditPage {

  public myForm:FormGroup;//form表单中的值
  //user:User;
  validation_messages = {
    'nickName': '昵称不能为空',
    'mobileNumber': '手机号码格式不正确',
    'mail':'邮箱格式不正确'
  };
  cityColumns: any[];

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              public formBuilder:FormBuilder,
              private userInfoService: UserInfoService,
              private appService: AppService,
              private cityDataProvider: CityDataProvider) {
    //this.user = this.userInfoService.user;
    //行政区划数据初始化
    this.cityColumns = this.cityDataProvider.cities;

    this.myForm=this.formBuilder.group({
      nickName:[this.userInfoService.user.nickName,Validators.required],
      gender:[this.userInfoService.user.gender],
      mobileNumber:[this.userInfoService.user.mobileNumber,[CustomValidators.phone('CN'),CustomValidators.rangeLength([11,11])]],
      mail:[this.userInfoService.user.mail,CustomValidators.email],
      birthday:[this.userInfoService.user.birthday],
      cityCode:[this.cityDataProvider.getCompleteCodeByArea(this.userInfoService.user.areaCode)],
    });

    console.log(this.userInfoService);
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad UserInfoEditPage');
  }

  //保存
  save(){
    let formModel = this.myForm.value;
    console.log(formModel);
    if(this.appService.validate(this.myForm,this.validation_messages)){
      //将form表单内容与userInfo数据模型进行同步
      this.saveToDataModel(formModel);
      this.userInfoService.updateUserToServer((data)=>{
        this.navCtrl.pop();//返回上一页
      });

    }
  }

  saveToDataModel(formModel:any){
    this.userInfoService.user.nickName = formModel.nickName;
    this.userInfoService.user.gender = formModel.gender;
    this.userInfoService.user.mail = formModel.mail;
    this.userInfoService.user.mobileNumber = formModel.mobileNumber;
    this.userInfoService.user.birthday = formModel.birthday;
    this.userInfoService.user.areaCode = formModel.cityCode.split(' ')[2];//只获取区级编码
  }

}
